# -*- coding: utf8 -*-
#!/usr/bin/env python

import os
import sys
import random
import urllib
import urllib2
import cookielib
import MySQLdb
from types import *
from urllib import urlencode


TEST = False
if TEST:
    DATABASE={
        'host':'',
        'user':'',
        'pass':'',
        'db':''
        }
else:
    DATABASE={
        'host':'',
        'user':'',
        'pass':'',
        'db':''
        }
def readDB(sql,setnames=True):
    """ 从mysql中读取一条数据 """
    try:
        conn = MySQLdb.connect(DATABASE['host'],DATABASE['user'],DATABASE['pass'],DATABASE['db'])
    except MySQLdb.Error, e:
        sys.exit(__file__+': '+str(e))
    cursor = conn.cursor ()
    if setnames:
        cursor.execute('set names utf8')
    cursor.execute(sql)
    rs=cursor.fetchone()
    if rs==None:
        return None
    result = {}
    i = 0
    for item in cursor.description:
        result[item[0]] = rs[i]
        i += 1
    conn.close()
    return result
def readAllDB(sql,setnames=True):
    """ 从mysql中读取所有结果 """
    try:
        conn = MySQLdb.connect(DATABASE['host'],DATABASE['user'],DATABASE['pass'],DATABASE['db'])
    except MySQLdb.Error, e:
        sys.exit(__file__+': '+str(e))

    cursor = conn.cursor ()
    if setnames:
        cursor.execute('set names utf8')
    cursor.execute(sql)
    rs=cursor.fetchall()
    index = []
    for item in cursor.description:
        index.append(item[0])
    conn.close()
    resultlist = []
    for i in rs:
        j = 0
        result = {}
        for item in i:
            result[index[j]] = item
            j = j+1
        resultlist.append(result)
    return resultlist
def LoadFile(filename, mode='r'):
    """安全读取文件内容
    1.安全读取文件,并返回文件内容.
    2.open 函数可能引发 IOError 异常。(可能是文件不存在。) 
    3.read 方法可能引发 IOError 异常。(可能磁盘有坏扇区，或它在一个网络驱动器上，而网络刚好断了。) 
    4.一旦文件通过 open 函数被成功地打开，我们应该绝对保证把它关闭，即使是在 seek 或 read 方法引发了一个异常时。try...finally 块可以用来：在 finally 块中的代码将总是 被执行，甚至某些东西在 try 块中引发一个异常也会执行。可以这样考虑，不管在路上发生什么，代码都会被 “即将灭亡” 地执行。 
    5.最后，处理我们的 IOError 异常。它可能是由调用 open、seek 或 read 引发的 IOError 异常。这里，我们其实不用关心，因为将要做的事就是静静地忽略它然后继续。(记住，pass 是一条不做任何事的 Python 语句。) 这样完全合法，“处理” 一个异常可以明确表示不做任何事。它仍然被认为处理过了，并且处理将正常继续，从 try...except 块的下一行代码开始。  
    """
    content = ''
    try:
        fp = open(filename, mode)
        try:
            content = fp.read()
        finally:
            fp.close()
    except IOError, e:
        print '#Error:', 'open '+filename, str(e)
    return content
def WriteFile(filename, content, mode='w'):
    """ 安全写入文件，对异常进行恰当的处理 """
    dirname = os.path.dirname(filename)
    if not os.path.isdir(dirname):
        os.makedirs(dirname)
    try:
        fp = open(filename, mode)
        try:
            fp.write(content)
        finally:
            fp.close()
    except IOError, e:
        print '#Error:', 'open '+filename, str(e)
def HttpDownload(url):
    """下载http页面文件
    安全下载http页面文件,增加异常判断和处理
    """
    content = ''
#    req = urllib2.Request(url)
    try:
        fp = urllib2.urlopen(url)
        try:
            content = fp.read()
        finally:
            fp.close()
    except Exception, e:
        print '#Error: open',url,'failed!',str(e)
    return content
def dprint(content):
    """输出变量内容
    针对list tuple dict的元素单独使用print,用于调试时查看非Ascii内容
    """
    conType = type(content)
    if conType in [TupleType,ListType]:
        for i in content:
            dprint(i)
    elif conType is DictType:
        for name,value in content.items():
            if name in [TupleType,ListType,DictType]:
                dprint(name)
            else:
                print str(name)+':',
                dprint(value)
    else:
        print content
def Login(url, userinfo):
    cj = cookielib.LWPCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    urllib2.install_opener(opener)
    opener.addheaders = [\
        ("User-agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.5) Gecko/20031107 Debian/1.5-3"),\
        ("Accept", "text/html, image/jpeg, image/png, text/*, image/*, */*")]
    postdata = urlencode(userinfo)
    r = opener.open(url,urlencode(userinfo))
def LoadDic(dataname,k=0,delimiter='\t'):
    dic= {}
    if not os.path.exists(dataname):
        return dic
    for line in open(dataname):
        try :
            segs = line.split(delimiter)
            dic[segs[k]] = segs 
        except:
            print line 
    return dic
def LoadList(dataname,sep='\n'):
    list = []
    if not os.path.exists(dataname):
        return list
    content = LoadFile(dataname)
    list = content.split(sep)
    while '' in list:
        list.remove('')
    return list
def Percent(a,b,n=2):
    """生成a/b之后的百分比，最多保留小数点后n位
    """
    result = ''
    if b==0:
        result = '0%'
    else:
        c = float(a)/b*100
        c = round(c,n)
        result = str(c)+'%'
    return result

if __name__=='__main__':
    print 'Test Util Start:'
    print HttpDownload('http://www.baidu.com')
